﻿#include "xplay.h"
#include "ffmpeg.h"
#include "xaudio.h"

#include <list>
#include <QDebug>

namespace HeaderMedia {

static std::list<AVPacket> g_videos;

XPlay::XPlay() : xIsStart(true) {
}

XPlay::~XPlay() {
}

void XPlay::run() {
  char out[10000] = {0};

  while (xIsStart) {
    if (!FFmpeg::getInstance().isPlay()) {
      msleep(10);
      continue;
    }

    while (g_videos.size() > 0) {
      AVPacket pack = g_videos.front();
      int pts = FFmpeg::getInstance().getPts(&pack);

      FFmpeg::getInstance().decode(&pack);
      av_packet_unref(&pack);
      g_videos.pop_front();
    }

    int free = XAudio::getInstance().getFree();
    if (free < 10000) {
      msleep(1);
      continue;
    }

    bool ok;
    AVPacket pkt = FFmpeg::getInstance().read(ok);
    if (pkt.size <= 0) {
      msleep(10);
    }

    if (pkt.stream_index == FFmpeg::getInstance().audioStream()) {
      FFmpeg::getInstance().decode(&pkt);
      av_packet_unref(&pkt);
      // 转换音频
      int len = FFmpeg::getInstance().toPCM(out);
      // 播放音频
      XAudio::getInstance().write(out, len);
      continue;
    }

    if (pkt.stream_index != FFmpeg::getInstance().videoStream()) {
      av_packet_unref(&pkt);
      continue;
    }

    g_videos.push_back(pkt);
  }
}

void XPlay::myStart() {
  xIsStart = true;
  start();
}

void XPlay::myStop() {
  xIsStart = false;
  exit();
}
} // namespace HeaderMedia
